package com.jweb.util;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池工具类
 * 
 * @author Yuanqy
 *
 */
public class ThreadPoolUtil {

	private static ExecutorService service = null;
	private static BlockingQueue<Runnable> queue = null;

	public static void init(int nThreads, int queueSize) {
		if (service == null) {
			queue = new ArrayBlockingQueue<>(10000);// 数组 有界队列
			service = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, queue);
		}
	}

	public static void init(int nThreads) {
		if (service == null) {
			queue = new LinkedBlockingQueue<>();// 链表 无界队列,【默认】
			service = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, queue);
			// service = Executors.newFixedThreadPool(nThreads); //等同于
		}
	}

	public static int getQueueSize() {
		return queue.size();
	}

	private static ExecutorService getInstance() {
		if (service == null)
			throw new NullPointerException("线程池未初始化，请先初始化！");
		return service;
	}

	public static boolean execute(Runnable runnalbe) {
		boolean flag = true;
		try {
			getInstance().execute(runnalbe);
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}

	public static void shutdown() {
		if (service != null) {
			System.err.println("=========[警告]线程池正在关闭[待所有线程执行完毕后]============");
			service.shutdown();
		}
	}
	public static void shutdownNow() {
		if (service != null) {
			System.err.println("=========[警告]线程池正在关闭[强制当前立即关闭]============");
			service.shutdownNow();
		}
	}

	public static void main(String[] args) {
		ThreadPoolUtil.init(10, 50);
		for (int i = 0; i < 130; i++) {
			ThreadPoolUtil.execute(new Thread() {
				@Override
				public void run() {
					try {
						Thread.currentThread().sleep(1500);
						System.out.println(Thread.currentThread().getName() + " Thread" + ThreadPoolUtil.getQueueSize());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
		System.out.println("线程加入完毕");
	}
}
